<?php


namespace App\Helpers\V1;


use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Validator;

class AuthMenuHelper
{
    /**
     * 递归生成无限级分类
     * @param Collection $list
     * @param int $pid
     * @param string $parent_name
     * @return array
     */
    public static function getTree(Collection $list, $pid = 0, $parent_name = '') : array
    {
        $tree = [];
        foreach($list as $key => $item) {
            if ($item->pid == $pid) {
                $tree[] = array(
                    'id' => $item->id,
                    "pid" => $item->pid,
                    "parent_name" => $parent_name,
                    'name' => $item->name,
                    "flag" => $item->flag,
                    'children' => self::getTree($list, $item->id, $item->name),
                );
            }
        }
        return $tree;
    }

    /**
     * 验证表单
     */
    public static function validateData($data)
    {
        $validator = Validator::make($data, [
            "pid" => "required",
            "name" => "required",
            "flag" => "required"
        ], [
            "pid.*" => "请选择上级功能",
            "name.*" => "请填写功能名称",
            "flag.*" => "请填写标识"
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first());
        }
    }
}
